package com.open.capacity.user.service.impl;

import com.open.capacity.common.model.TitleRule;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.user.dao.TitleRuleDao;
import com.open.capacity.user.service.TitleRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author liutao
 * @date 2021-02-23 09:41
 */
@Service
public class TitleRuleServiceImpl implements TitleRuleService {

    @Autowired
    private TitleRuleDao titleRuleDao;

    @Override
    public PageResult<TitleRule> getSelectTitleRules(Map<String, Object> params) {
        int count = titleRuleDao.count(params);
        PageUtil.pageParamConver(params,true);
        List<TitleRule> titleRules = titleRuleDao.getSelectTitleRules(params);
        return PageResult.<TitleRule>builder().code(0).
                data(titleRules).count((long) count).build();
    }

    @Override
    public Result addTitleRules(TitleRule titleRule) {
        boolean isCodeExist = isCodeExist(titleRule.getTtcode(),null);
        if (isCodeExist){
            return Result.failed("该code已存在");
        }
        if (isPointsExist(titleRule.getPoints(),null,titleRule.getTttype(),titleRule.getRoleid())){
            return Result.failed("该积分值已存在");
        }

        int result = titleRuleDao.addTitleRules(titleRule);
        return Result.succeed(result == 1 ? "添加成功" : "添加失败");
    }

    private boolean isCodeExist(String ttcode,Integer ttruid) {
        return titleRuleDao.isCodeExist(ttcode, ttruid) > 0;
    }

    private boolean isPointsExist(Integer points,Integer ttruid,Integer typeId,Integer roleId) {
        return titleRuleDao.isPointsExist(points, ttruid,typeId,roleId) > 0;
    }

    @Override
    public Result updateTitleRules(TitleRule titleRule) {
        if(isCodeExist(titleRule.getTtcode(),titleRule.getTtruid())){
            return Result.failed("该code已存在");
        }
        if (isPointsExist(titleRule.getPoints(),titleRule.getTtruid(),titleRule.getTttype(),titleRule.getRoleid())){
            return Result.failed("该积分值已存在");
        }
        int result = titleRuleDao.updateTitleRules(titleRule);
        return Result.succeed(result == 1 ? "修改成功" : "修改失败");
    }

    @Override
    public Result delTitleRules(int ttruid) {
        int result = titleRuleDao.delTitleRules(ttruid);
        return Result.succeed(result > 0?"删除成功":"删除失败");
    }
}
